/**
 *   This file is part of WiFiStorer.

    WiFiStorer is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    WiFiStorer is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with WiFiStorer.  If not, see <http://www.gnu.org/licenses/>.
    
    @author Ontic Soluciones
    @license GNU GPLv3
    @copyright 2010 Ontic Soluciones
    @link http://www.ontic.es
    @contact android@ontic.es
 */


package com.Storer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;


/**
 * Clase que implementa la posibilidad de enviar nuestro Kml por email.
 * 
 * @author Ontic Soluciones
 *
 */
public class SendKml extends ListActivity {	

	private ArrayList<String> tablas = new ArrayList<String>();
	private List<String> vista = new ArrayList<String>();
	private SQLiteDatabase DB;
	private DataBaseHelper db;
	private Context context;
	private String s;
	private String result="";
	private 	  String aux;

	/**
	 * Llamado al crear la actividad.
	 * Hace un ls en la carpeta donde las guarda por defecto, así si detecta un fichero con el mismo
	 * nombre muestra un asterisco (*) para avisar al usuario de que esa tabla ya está exportada.
	 * Luego crea una instancia de la clase que exporta y muestra un mensaje final.
	 */
	public void onCreate(Bundle savedInstanceState)
	{
      super.onCreate(savedInstanceState);
      
      db = new DataBaseHelper(this);
      DB = db.getReadableDatabase();
	  context = (this);      


		try {
			Process p = Runtime.getRuntime().exec("ls "+Environment.getExternalStorageDirectory().getAbsolutePath()+"/kmls");

			BufferedReader stdInput = new BufferedReader(new InputStreamReader(
			                p.getInputStream()));

			while ((s = stdInput.readLine()) != null) 
			{
			       result+= " "+s;
			}
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
      
      Cursor tables = DB.rawQuery("select * from sqlite_sequence",null);
      tables.moveToFirst();
      
      if(tables.moveToFirst())
      for(int i =0; i<tables.getCount(); i++)
      {
    	  aux = tables.getString(0);
    	  if(aux.charAt(0)== 't')
    	  {
    		  aux = aux.substring(1);
    		  vista.add(""+aux.substring(6)+"/"+aux.substring(4, 6)+"/"+aux.substring(0, 4)); 
    		  tablas.add(aux);
    	  }
    	  tables.moveToNext();
      }

      DB.close();
      ListView lv = getListView();
      lv.setTextFilterEnabled(true);

      setListAdapter(new ArrayAdapter<String>(this, R.layout.lista_wifis, vista));
    
      lv.setOnItemClickListener(new OnItemClickListener() 
      {
        public void onItemClick(AdapterView<?> parent, View view,
            int position, long id)
        {    	        	
			
			Intent sendIntent = new Intent(Intent.ACTION_SEND);
			sendIntent.putExtra(Intent.EXTRA_SUBJECT, tablas.get(position)+" Kml");
			sendIntent.setType("text/kml");
			
			sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://"
						+ Environment.getExternalStorageDirectory()
						+ "/kmls/t"+tablas.get(position)+".kml"));
			
			sendIntent.putExtra(Intent.EXTRA_STREAM, Uri
						.parse("file:///sdcard/kmls/t"+tablas.get(position)+".kml"));
			
			context.startActivity(Intent.createChooser(sendIntent,
					"KmlSend"));
	   	    finish();
        }
      });
    }
	
	/**
	 * Crea el menú cuando le damos a la tecla.
	 */
	public boolean onCreateOptionsMenu(Menu menu) 
	{
        menu.add(0, 2, 0, R.string.draw_map).setIcon(android.R.drawable.ic_menu_mapmode);
        menu.add(0, 4, 0, R.string.sendKml).setIcon(android.R.drawable.ic_dialog_email);
		
        return(super.onCreateOptionsMenu(menu));
    }
    

	/**
	 * Detecta qué opción se pulsó y lanza la actividad correspondiente.
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) 
	{
	    // Handle item selection
	    switch (item.getItemId()) {

	    case 2:
	    	Intent intent = new Intent(this,PintaMapa.class);
			startActivity(intent);
			finish();
			
	    case 4: 
	    	Intent inte = new Intent(this, SendKml.class);
	    	startActivity(inte);
	    	finish();
	    	
	    default:
	        return super.onOptionsItemSelected(item);
	    }
	}
	
	public void onPause()
	{
		super.onPause();
	}
	

}
